# !/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
from model import Schema, Table, Column, Template, ClassEncoder
from jinja2 import Environment
from pathlib import Path
from typing import List
from util.func import Func

def types(columns: list):
    type_list = []
    for column in columns:
        if column['type'] not in type_list:
            type_list.append(column['type'])
    return type_list    


def get_types(_type: str):
    if _type == '':
        return {}
    with open("types/" + _type + ".json", 'r', encoding="utf-8") as f:
        return json.load(f)


def render(env: Environment, table: Table, tpl: Template, out_dir: str):
    ss = json.dumps(table, cls=ClassEncoder)
    data_json = json.loads(ss)
    module = Func.name(tpl.name)

    if tpl.module != '':
        module = "/".join(list(tpl.module.split(".")))

    # 获取一个模板文件
    template = env.get_template(tpl.name)
    types = get_types(tpl.type)
    # 渲染
    s = template.render(table=data_json, type=types, func=Func)
    file_name = table.name
    if tpl.name_type == 'alias':
        file_name = table.alias
    if tpl.name_type == 'camel':
        file_name = table.camel
    out_file = out_dir + module + "/" + tpl.prefix + file_name + tpl.suffix + "." + tpl.file_type
    write_file(out_file, s)
    return s


def render_schema(env: Environment, schema: Schema, tpl: str, filename=str):
    ss = json.dumps(schema, cls=ClassEncoder)
    data_json = json.loads(ss)
    # 获取一个模板文件
    template = env.get_template(tpl)
    # 渲染
    s = template.render(schema=data_json, func=Func)
    write_file(filename, s)
    return s


def parse(schema_json):
    tables: List[Table] = list()
    for t in schema_json['tables']:
        columns: List[Column] = list()
        for c in t['columns']:
            # print(c)
            column = Column(c['name'], c['type'], c['size'])
            column.default = c.get('default') if c.get('default') is not None else ''
            column.require = c.get('require') if c.get('require') is not None else False
            column.comment = c.get('comment') if c.get('comment') is not None else ''
            column.index = c.get('index') if c.get('index') is not None else ''
            column.auto_increment = c.get('auto_increment') if c.get('auto_increment') is not None else False
            column.form = c.get('form') if c.get('form') is not None else ''
            column.data = c.get('data') if c.get('data') is not None else []
            column.ref = c.get('ref') if c.get('ref') is not None else ''
            columns.append(column)
        table = Table(t['table'], t['comment'], columns)
        table.enable = t.get('enable') if t.get('enable') is not None else True
        # print(table)
        tables.append(table)
    schema = Schema(schema_json['author'], schema_json['db'], tables)
    templates: List[Template] = list()
    for tpl in schema_json['templates']:
        template = Template(name=tpl['name'], file_type=tpl['file_type'], type=tpl['type'])
        template.prefix = tpl.get('prefix') if tpl.get('prefix') is not None else ''
        template.suffix = tpl.get('suffix') if tpl.get('suffix') is not None else ''
        template.module = tpl.get('module') if tpl.get('module') is not None else ''
        template.name_type = tpl.get('name_type') if tpl.get('name_type') is not None else 'name'
        template.enable = tpl.get('enable') if tpl.get('enable') is not None else True
        templates.append(template)
    schema.templates = templates
    schema.database = schema_json['database']
    schema.package = schema_json['package']
    schema.engines = schema_json['engines'] if schema_json['engines'] is not None else []
    return schema


# 清空文件夹
def clear_out():
    dir_path = Path('./out').absolute()
    for root, dirs, files in os.walk(dir_path, topdown=False):
        # 第一步：删除文件
        for name in files:
            os.remove(os.path.join(root, name))  # 删除文件
        # 第二步：删除空文件夹
        for name in dirs:
            os.rmdir(os.path.join(root, name))  # 删除一个空目录


def write_file(file, content):
    index = str(file).rfind("/")
    if index != -1 and not os.path.isdir(str(file)[0: index]):
        os.makedirs(str(file)[0: index])
    with open(file, 'w', encoding="utf-8") as f:
        f.write(content)
